package com.wnxy.controller;

import com.wnxy.entity.BookType;
import com.wnxy.mapper.BookTypeMapper;
import com.wnxy.service.BookTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 林夕
 * @since 2023-03-18 11:05:47
 */
@RestController
@RequestMapping("/bookType")
public class BookTypeController {
    @Autowired
    BookTypeService bookTypeService;
    @Autowired
    BookTypeMapper bookTypeMapper;
    @Autowired
    RedisTemplate<String, Object> stringObjectRedisTemplate;

    /* 拿到所有图书类型 */
    @RequestMapping("getTypes")
    public List<BookType> getTypes(){
        List<BookType> bookTypeList = new ArrayList<>();
        if (stringObjectRedisTemplate.opsForValue().get("bookType") == null){
            bookTypeList = bookTypeService.list();
            stringObjectRedisTemplate.opsForValue().set("bookType",bookTypeList);
        }else {
            bookTypeList = (List<BookType>) stringObjectRedisTemplate.opsForValue().get("bookType");
        }
        return bookTypeList;
    }

    /* 根据id查询单个图书类型 */
    @RequestMapping("getOne")
    public BookType getOne(Integer typeId){
        BookType bookType = bookTypeMapper.selectById(typeId);
        return bookType;
    }

    /* 修改图书类型 */
    @RequestMapping("update")
    public void update(BookType bookType){
        BookType bookType1 = bookTypeMapper.selectById(bookType.getId());
        bookType.setCreateTime(bookType1.getCreateTime());
        bookType.setUpdatetime(new Date());
        bookTypeMapper.updateById(bookType);
        stringObjectRedisTemplate.delete("bookType");
    }

    /* 删除图书类型 */
    @RequestMapping("delete")
    public void delete(Integer typeId){
        bookTypeMapper.deleteById(typeId);
        stringObjectRedisTemplate.delete("bookType");
    }

    /* 增加图书类型 */
    @RequestMapping("add")
    public void add(String name){
        BookType bookType = new BookType();
        bookType.setName(name);
        bookType.setCreateTime(new Date());
        bookType.setUpdatetime(new Date());
        bookTypeMapper.insert(bookType);
        stringObjectRedisTemplate.delete("bookType");
    }
}
